<template>
  <div class="mark_com" :style="{ width: GCanvasSize.wS + 'px', height: GCanvasSize.hS + 'px' }">
    <img class="canvas_bg" :src="srcInfo.taskPicUrl" alt="">
    <canvas :id="id" :width="GCanvasSize.wS" :height="GCanvasSize.hS"></canvas>
  </div>
</template>

<script>
import { fabric } from 'fabric'
import { mapGetters } from 'vuex'
export default {
  props: {
    id: {
      type: String,
      default: ''
    },
    srcInfo: {
      type: Object,
      default () {
        return {
          markPrice: 0,
          taskPicUrl: null
        }
      }
    }
  },
  computed: {
    ...mapGetters(['GCanvasSize'])
  },
  data () {
    return {
      canvasId: null,
      mainPicObj: null
    }
  },
  methods: {
    handleUpdatePrice () {
      this.canvasId.forEachObject(item => {
        if (item.myPrice) {
          item.set({
            text: this.srcInfo.markPrice + '',
            dirty: true
          })
          this.canvasId.renderAll()
        }
      })
    },
    handleParseJson (jsonStr) {
      if (this.canvasId) {
        this.canvasId.clear()
      } else {
        this.canvasId = new fabric.Canvas(this.id, { selection: false })
      }
      this.canvasId.loadFromJSON(jsonStr, () => {
        this.canvasId.selectable = false
        this.canvasId.setZoom(this.GCanvasSize.scaleS * this.GCanvasSize.scaleLoad)
        this.handleUpdatePrice()
      })
    },
    dataURLtoBlob (dataurl) {
      var arr = dataurl.split(',')
      var mime = arr[0].match(/:(.*?);/)[1]
      var bstr = atob(arr[1])
      var n = bstr.length
      var u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: mime })
    },
    handleToJson () {
      if (!this.canvasId) this.canvasId = new fabric.Canvas(this.id, { selection: false })
      return JSON.stringify(this.canvasId.toJSON(['myPrice', 'myTmp', 'params']))
    },
    onSave (canvasId) {
      canvasId.width = this
      canvasId.height = 500
      canvasId.setZoom(1)
      const url = canvasId.toDataURL()
      const blob = this.dataURLtoBlob(url)
      // a标签下载
      const elink = document.createElement('a')
      elink.download = '截图.png'
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      document.body.removeChild(elink)
    }
  }
}
</script>

<style lang="less" scoped>
.mark_com {
  position: relative;
  .canvas_bg {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    img {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
